package org.jeecgframework.web.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.UploadChangeRecordService;
import org.jeecgframework.web.system.pojo.base.UploadChangeRecordThread;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentTypeEntity;
import org.jeecgframework.web.system.pojo.base.ZySpareRecordEntity;
import org.jeecgframework.web.system.pojo.base.ZyUpFactoryRecordThread;
import org.jeecgframework.web.util.ExcelUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**   
 * @Title: UploadChangeRecordService
 * @Description: 备件更换记录
 * @author ZhangYunlong
 * @date 2016-04-01
 * @version V1.0   
 *
 */
@Service("uploadChangeRecordService")
@Transactional
public class UploadChangeRecordServiceImpl extends CommonServiceImpl implements UploadChangeRecordService {

	/**
	 * @Description 解析EXCEL
	 * @param HttpServletRequest 通过前台请求获得文件流
	 */
	@Override
	public void parseExcel(HttpServletRequest req) {
		try {
			System.out.println("开始解析");
			String filePath = req.getParameter("filePath");
			List<Map<String, Object>> mapList = ExcelUtil.analyzeExcel(filePath, "1");
			List<ZySpareRecordEntity> result = new ArrayList<ZySpareRecordEntity>();
			List<ZyEquipmentSpareEntity> esSpareList = new ArrayList<ZyEquipmentSpareEntity>();
			Map<String, List<Map<String,Object>>> spareListMap = new HashMap<String, List<Map<String,Object>>>();
			
			List<ZyEquipmentSpareEntity> esLists = super.getList(ZyEquipmentSpareEntity.class);
			List<ZyEquipmentTypeEntity> etLists = super.getList(ZyEquipmentTypeEntity.class);
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" 	et.type_desc ");
			sql.append(" FROM ");
			sql.append(" 	zy_equipment_spare es ");
			sql.append(" LEFT JOIN zy_equipment_type et on et.id = es.type ");
			sql.append(" WHERE ");
			sql.append(" 	es.top_item_sn = ? ");
			sql.append(" AND !ISNULL(type_desc) ");
			for (int i = 1; i < mapList.size(); i++) {
				Map<String, Object> map = mapList.get(i);
				ZySpareRecordEntity zySpareRecordEntity = new ZySpareRecordEntity();
				String snCellVal = StringUtil.getString(map.get("0"));
				ZyEquipmentSpareEntity zyEs = null;
				for (ZyEquipmentSpareEntity es : esLists) {
					if(es.getSn().equals(snCellVal)){
						zyEs = es;
						break;
					}
				}
				
				String type = StringUtil.getString(map.get("1"));
				String equipmentSn = zyEs != null ? zyEs.getSn() : null;
        		zySpareRecordEntity.setEquipmentSn(equipmentSn);
        		zySpareRecordEntity.setCinemaId(zyEs != null ? zyEs.getZyCinema() : null);
        		ZyEquipmentTypeEntity zyEt = null;
        		for (ZyEquipmentTypeEntity et : etLists) {
					if(et.getTypeDesc().equals(type)){
						zyEt = et;
						break;
					}
				}
        		zySpareRecordEntity.setSpareDesc(zyEt);
        		String oldSnVal = StringUtil.getString(map.get("2"));//
        		zySpareRecordEntity.setOldSpareSn(oldSnVal);
        		String oldItemVal = StringUtil.getString(map.get("3"));//
        		zySpareRecordEntity.setOldSpareNo(oldItemVal);
        		zySpareRecordEntity.setReplaceDate(DateUtils.str2Date(map.get("4").toString(), DateUtils.sdf_date_1));
        		String newSnVal = StringUtil.getString(map.get("5"));//
        		zySpareRecordEntity.setNewSpareSn(newSnVal);
        		String newItemVal = StringUtil.getString(map.get("6"));//
        		zySpareRecordEntity.setNewSpareNo(newItemVal);
        		zySpareRecordEntity.setReplaceReason(StringUtil.getString(map.get("7")));
        		zySpareRecordEntity.setRemark(StringUtil.getString(map.get("8")));
        		zySpareRecordEntity.setRelationServiceNo(StringUtil.getString(map.get("9")));
        		result.add(zySpareRecordEntity);
        		List<Map<String, Object>> rsMapList = new ArrayList<Map<String,Object>>();
        		//根据SN查询出来的结果放入map 。避免多次查询数据库
        		if(spareListMap.size() > 0 && spareListMap.get(snCellVal) != null){
        			rsMapList = spareListMap.get(snCellVal);
        		}else{
        			rsMapList = super.findForJdbc(sql.toString(), snCellVal);
        			spareListMap.put(snCellVal, rsMapList);
        		}
        		boolean hadSpare = false;
        		if(null != rsMapList){
        			for (Map<String, Object> mp : rsMapList) {
        				if(null != mp.get("type_desc") && null != zyEt 
        						&& mp.get("type_desc").toString().equals(zyEt.getTypeDesc())){
        					hadSpare = true;
        					break;
        				}
        			}
        		}
        		if(!hadSpare){
        			ZyEquipmentSpareEntity esSpare = new ZyEquipmentSpareEntity();
        			esSpare.setSn(newSnVal);
        			esSpare.setType(zyEt);
        			esSpare.setItem(newItemVal);
        			esSpare.setTopItemSn(snCellVal);
        			esSpare.setServerState(StaticValue.DIC_SERVER_STATE_1001);
        			esSpare.setIsServicing("0");
        			esSpare.setIsNormal("0");
        			esSpare.setIsSpare(true);
        			esSpare.setRepairDate(0);
        			esSpareList.add(esSpare);
        		}
        		//更新设备的备件
        		super.executeSql("UPDATE zy_equipment_spare SET sn = ?,item = ? WHERE top_item_sn = ? AND sn = ? ",newSnVal,newItemVal,equipmentSn,oldSnVal);
			}
			System.out.println("开始保存");
			super.batchSave(result);
			super.batchSave(esSpareList);
			System.out.println("新增设备的备件数量：" + esSpareList.size());
			System.out.println("保存完毕了");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * @Description 将通过POI解析出来的EXCEL转换成对应的实体LIST
	 * @param XSSFWorkbook Excel2007+对象
	 */
//	private void parseExcelToList(XSSFWorkbook hwb){
//		
//		//得到第一个工作表   
//		XSSFSheet  sheet = hwb.getSheetAt(0);
//		int maxUnit = 2000;
//		int countRow = sheet.getPhysicalNumberOfRows();
//		int threadC = countRow / maxUnit;
//		int points = countRow % maxUnit;
//		if(threadC > 0){
//			if(points > 0){
//				threadC = threadC + 1;
//			}
//		}else{
//			threadC = 1;
//		}
//		System.out.println("threadC:" + threadC);
//		for (int i = 0; i < threadC; i++) {
//			int beginR = i == 0 ? 1 : i * maxUnit + 1;
//			int endR = i == (threadC -1 ) ? countRow : beginR + maxUnit - 1 ;
//			UploadChangeRecordThread upChangeRecordThread = new UploadChangeRecordThread(beginR,endR,sheet);
//			upChangeRecordThread.start();
//		}
//	} 

}
